package org.lisy.java.io;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.csvreader.CsvWriter;

/**
 * CsvWriter 文件生成
 * 
 * @author lisy
 */
public class CsvOperate {

	// 目标CSV文件目录
	private final static String TARGET_CSV_FILE_DIR = "./deploy/target/csv";
	// 目标CSV文件
	private final static String TARGET_CSV_FILE = "target.csv";
	
	public static void main(String[] args) {
		// 获取标题
		List<String> head = getHead();
		
		// 获取数据
		List<List<String>> date = getData();
		
		// 准备生成文件
		writeFile(head, date);
	}

	/**
	 * 获取文件标题
	 * @return
	 */
	private static List<String> getHead() {
		List<String> head = new ArrayList<String>();
		for (int i = 0; i < 10; i++) {
			head.add("title" + (i + 1));
		}
		return head;
	}
	
	/**
	 * 获取文件数据
	 * @return
	 */
	private static List<List<String>> getData() {
		List<List<String>> date = new ArrayList<List<String>>();
		for (int i = 0; i < 10000; i++) {
			List<String> row = new ArrayList<String>();
			for (int j = 0; j < 10; j++) {
				if (i == 1 && j == 1) {
					row.add(" %% \\//^`\"' " + "\r\n" + " ");	
				} else {
					row.add((i+1) + "_" + (j+1));	
				}
			}
			date.add(row);
		}
		return date;
	}

	/**
	 * 生成文件
	 * @param head
	 * @param date
	 */
	private static void writeFile(List<String> head, List<List<String>> date) {
		CsvWriter csvWriter = null;
		try {
			long startTime = System.currentTimeMillis();
			String filePath = TARGET_CSV_FILE_DIR + File.separator + TARGET_CSV_FILE;
			File file = new File(filePath);
			if (!file.exists()) {
				// 如果上级不存在，就会自动创建
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			csvWriter = new CsvWriter(filePath, ',', Charset.forName("UTF-8"));
			// 跳过数据校验(空格)
			// 写入标题
            csvWriter.writeRecord(head.toArray(new String[head.size()]), true);
			// 逐行写入数据
            int num = 0;
            for (int i = 0; i < date.size(); i++) {
            	List<String> list = date.get(i);
            	String[] dataArr = list.toArray(new String[list.size()]);
    			csvWriter.writeRecord(dataArr, true);
    			num++;
			}
			System.out.println("File export finish! NUM:" + num +", TC:" + (System.currentTimeMillis() - startTime));
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("File export exception! " + e.toString());
		} finally {
			if (csvWriter != null) {
				csvWriter.close();
			}
		}
	}
	
}
